﻿/*==============================
 * 项目：JS结构性开发框架
 * 作者：胡炯（炯炯侠）
 * QQ：41200414
 * 最后修改时间：20120521
 * 修改目标：增加启动信息
 ==============================*/
 
(function(_w) {

    //var is_route = false;
    var is_route = true;

    //var is_debug = false;
    var is_debug = true;

    var default_hash = '#!/index/index';

    _w.Debug = new function() {

        var console = {
            'info': function() { },
            'time': function() { },
            'timeEnd': function() { },
            'runtimeobj': {}
        };

        if (!is_debug) return console;

        if (window.console) {
            console = window.console;
        }
        else {
            console = {
                'info': function(_msg) {
                    var divConsole = document.getElementById('div_console')
                    if (!divConsole) {
                        divConsole = document.createElement('div');
                        divConsole.id = 'div_console';
                        document.body.appendChild(divConsole);
                    }
                    divConsole.innerHTML += _msg + '<br />';
                },
                'time': function() { },
                'timeEnd': function() { },
                'runtimeobj': {}
            };
        }

        return console;
    };

    _w.MPT = new function() {
        this.Config = {};

        var _self = this;
        var actions = {};
        var layout_list = {};
        var current_layout = null;
        var route_list = {};
        var tmpl_list = {};
        var model_list = {};
        var class_list = {};
        var object_list = {};

        var layout_map = {
            "index": "ly4",
            "register": "ly4",
            "guide": "ly4",
            "myspace": "ly121_1",
            "signin": "ly13_1",
            "profile": "ly13_1",
            "friend": "ly4_2",
            "topic": "ly121_1",
            "gift": "ly13_1",
            "rank": "ly4",
            "mission": "ly13_1",
            "message": "ly13_1",
            "shop": "ly4",
            "app": "ly13_3",
            "welcome": "ly4",
            "help": "ly4",
            "uspace": "ly121_2",
            "uprofile": "ly13_2",
            "ufriend": "ly13_2"
        };


        var assignClass = function() {
            for (var model_name in model_list) {
                _w[model_name] = model_list[model_name];
            }
            for (var class_name in class_list) {
                _w[class_name] = class_list[class_name];
            }
            for (var object_name in object_list) {
                _w[object_name] = object_list[object_name];
            }
        };

        this.getIsDebug = function() {
            return is_debug;
        };

        this.excAction = function(_context) {
            var actions_and_elms = getActionsAndElms(_context);

            for (var i = 0; i < actions_and_elms.length; i++) {
                Debug.info("[frame excAction] execute Action " + actions_and_elms[i]['action_name']);
                actions[actions_and_elms[i]['action_name']](actions_and_elms[i]['element']);
            }
        };

        var getActionsAndElms = function(_context) {
            var actions_and_elms = [];

            if (_context.getElementsByClassName)
                var elms = _context.getElementsByClassName("mpt");
            else
                var elms = _context.getElementsByTagName("*");



            var elms_length = elms.length;
            for (var i = 0; i < elms_length; i++) {
                var classname = elms[i].getAttribute("class") || elms[i].getAttribute("classname");
                if (!classname) continue;
                var reg = /\sa_(\w+)/;
                var action = classname.match(reg);
                if (action && action[1]) {
                    if (actions[action[1]]) {
                        actions_and_elms.push({
                            "action_name": action[1],
                            "element": elms[i]
                        });
                    }
                    else {
                        //throw "a_" + action[1] + " 未找到对应action";
                    }
                }
            }

            return actions_and_elms;
        };

        this.excRoute = function(_hash, _no_set_hash) {
            Debug.info("[frame excRoute] _hash: " + _hash);

            var hash_A = _hash.replace('#!/', '').split('/');

            if (hash_A.length >= 1 && hash_A.length <= 3) {
                if (hash_A.length == 1) hash_A.push('index');

                var route = hash_A[0];
                var layout = layout_map[hash_A[0]];
                var func = hash_A[1];
                var param = hash_A[2];

                if (!layout_list[layout]) {
                    throw "[frame excRoute] 未定义 " + layout + " Layout";
                    return;
                }

                if (!route_list[route]) {
                    throw "[frame excRoute] 未定义 " + route + " route";
                    return;
                }

                if (!route_list[route][func]) {
                    throw "[frame excRoute] " + route + ' route 未定义 ' + func + " 方法";
                    return;
                }

                if (current_layout != layout) {
                    Debug.info("[frame excRoute] " + layout + " replace #layout");
                    layout_list[layout](function() {
                        Debug.info("[frame excRoute] " + route + "_" + func + " replace #contenter");
                        route_list[route][func](param);
                    });

                    current_layout = layout;
                }
                else {
                    route_list[route][func](param);
                }

                if (!_no_set_hash) window.location.hash = _hash;
            }
        };

        this.bind = function(_obj, _type, _fun) {
            if (_obj.attachEvent) _obj.attachEvent("on" + _type, _fun);
            else _obj.addEventListener(_type, _fun, false);
        };

        this.addAction = function(_name, _fun) {
            Debug.info("[frame addAction] add Action " + _name);
            if (actions[_name]) {
                throw "动作 " + _name + " 重复定义！";
                return;
            }
            else {
                actions[_name] = _fun;
            }
        };

        var checkObjProperty = function(_obj, _key, _msg, _callbakck) {
            if (_obj.hasOwnProperty(_key)) {
                throw _msg;
                return;
            }
            else {
                _callbakck();
            }
        };

        this.addLayout = function(_name, _fun) {
            Debug.info("[frame addLayout] add Layout " + _name);

            checkObjProperty(layout_list, _name, "addLayout(\"" + _name + "\", ...) 添加布局重名！", function() {
                layout_list[_name] = _fun;
            });
        };

        this.addRoute = function(_name, _fun) {
            Debug.info("[frame addRoute] add Route " + _name);

            checkObjProperty(route_list, _name, "addRoute(\"" + _name + "\", ...) 添加路由重名！", function() {
                route_list[_name] = new _fun;
            });
        };

        this.addTmpl = function(_name, _fun) {
            Debug.info("[frame addTmpl] load templete " + _name + " success");

            checkObjProperty(tmpl_list, _name, "addTmpl(\"" + _name + "\", ...) 添加模板重名！", function() {
                tmpl_list[_name] = _fun;
            });
        };

        this.getTmpl = function(_name, _data) {
            return tmpl_list[_name]((!_data ? {} : _data));
        };

        this.addModel = function(_name, _fun) {
            Debug.info("[frame addModel] add Model " + _name);

            checkObjProperty(model_list, _name, "addModel(\"" + _name + "\", ...) 添加数据模型重名！", function() {
                model_list[_name] = new _fun;
            });
        };

        this.addClass = function(_name, _fun) {
            Debug.info("[frame addClass] add Class " + _name);

            checkObjProperty(class_list, _name, "addClass(\"" + _name + "\", ...) 添加类包重名！", function() {
                class_list[_name] = _fun;
            });
        };

        this.addObject = function(_name, _fun) {
            Debug.info("[frame addObject] add Object " + _name);

            checkObjProperty(object_list, _name, "addObject(\"" + _name + "\", ...) 添加对象重名！", function() {
                object_list[_name] = new _fun;
            });
        };

        var initHashChange = function() {
            var hash = default_hash;
            if (window.location.hash.replace('#!', '')) {  //hash不为空，必定不是首页，则进行登录判断
                hash = window.location.hash;

                //未登录状态下，跳转到首页
                var un_log_pages = [];
                
                if ($.inArray(hash, un_log_pages) == -1 && MPT.Config["session"]['userid'] == '') {
                    window.location.href = MPT.Config["url"]['index'];
                }
            }
            else {   //若hash为空，则可能为首页
                if (MPT.Config["session"]['userid'] != '') {
                    window.location.href = MPT.Config["url"]['myspace'];
                }
            }

            Debug.info(hash);

            jQuery("a[target='hashtarget']").live('click', function(event) {
                var match_hash = jQuery(this).attr('href').match(/\#\!.*/)[0];
                Debug.info(match_hash);

                if (jQuery.browser.safari || jQuery.browser.mozilla) {
                    window.location.hash = match_hash;
                }
                else {
                    document.getElementById("hashtarget").src = 'hp.html?_=' + Math.random() + match_hash;
                }

                event.preventDefault();
            });

            //Debug.info();
            if (jQuery.browser.safari || jQuery.browser.mozilla) {
                window.onhashchange = function() {
                    if (window.location.hash.replace('#!', '')) {
                        _self.excRoute(window.location.hash, true);
                    }
                    else {
                        _self.excRoute(default_hash, true);
                    }
                };
                _self.excRoute(hash, true);
            }
            else {
                jQuery('body').append('<iframe frameborder="0" id="hashtarget" name="hashtarget" width="1" height="1" src="hp.html?_=' + Math.random() + hash + '"></iframe>');
            }
        };

        this.start = function() {
            assignClass();

            if (is_route) {
                initHashChange();
            }
            else {
                _self.excAction(document);
            }
        };
    };

    _w.MPT.bind(_w, "load", function() {
        _w.MPT.start();
    });

})(window);
